{% extends 'IcsocUIBundle::page.html.twig' %}
{% from 'IcsocUIBundle:Macro:grid.html.twig' import gridWidth,gridNav,gridConfig %}
{% from 'IcsocUIBundle:Macro:actions.html.twig' import timebutton,searchtime,searchForm,searchFormBtn,playSound %}
{% block stylesheet %}
    {{ parent() }}
    {% stylesheets
    '@datepicker_css'
    '@jqgird_css'
    '@jquery_ui_css'
    '@gritter_css'
    '@chosen_css'
    filter='cssrewrite' filter='uglifycss'
    %}
    <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

{% block content %}
    <style type="text/css">
        .audios::-internal-media-controls-download-button {
            display:none;
        }
        .audios::-webkit-media-controls{overflow:hidden!important;}
        .audios::-webkit-media-controls-enclosure {
            width: calc(100% + 50px);
            margin-left: 30px;
        }
    </style>
    <form action="javascript:search()" method="post" id="searchForm">
        <div class="widget-container-col">
            <div class="widget-box">
                <div class="widget-body">
                    <div class="widget-main no-padding">
                        <table class="table table-bordered table-hover no-padding">
                            <tbody>
                            {{ timebutton() }}
                            {{ searchForm(options) }}
                            {{ searchtime(date.today.start, date.today.end) }}
                            {{ searchFormBtn() }}
                            {{ playSound() }}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
    {#<div>
        <button onclick="selectAll(1, true)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select all'|trans }}</button>
        <button onclick="selectAll(2)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select not all'|trans }}</button>
        {% if downSound %}
            <button onclick="batchDownload()" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Batch download'|trans }}</button>
        {% endif %}
        <span>你已经选择<b id="selectNum">0</b>行</span>
    </div>#}
    <div id="dialogconfirm" class="hide row">
        <div class="alert alert-block alert-success">
            <i class="ace-icon fa fa-check green"></i>
            由于数据量过大，下载任务转到<br>后台生成，点击进入生成界面查看进度。
            <i class="ace-icon fa fa-hand-o-right icon-animated-hand-pointer blue"></i>
            <a class="pink" href="#" onclick="showTab('下载任务管理', '{{ path('icsoc_security_develop_download_work_index') }}')" data-toggle="modal">查看进度</a>
        </div>
    </div>
{% endblock %}
{% block footer %}
    {% javascripts
    '@datepicker_js'
    '@jqgird_js'
    '@jquery_ui_js'
    '@gritter_js'
    '@common_js'
    '@chosen_js'
    filter='uglifyjs'
    %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script type="text/javascript">
    $(function () {
        $('#start_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
        $('#end_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
        $('.chosen-select').chosen({width: $(".col-sm-6").width()+'px', allow_single_deselect:true, no_results_text:'{{ 'Not found'|trans }}'});
    });
    var isSelectAll = 3;
    var isSelectedIds = []; //用于非全选用；
    var isCancelSelect = [];
    var countRecord = 0;
    var isSpecial = {{ isSpecial }};
    Array.prototype.remove=function(dx){
        if (isNaN(dx) || dx > this.length) {
            return false;
        }
        for (var i= 0,n=0;i<this.length;i++) {
            if (this[i] != this[dx]) {
                this[n++] = this[i]
            }
        }
        this.length-=1;
    };
    jQuery(function($) {
        //判断谷歌浏览器
        myBrowser();

        {{ gridWidth() }}
        jQuery(grid_selector).jqGrid({
            caption: "{{ 'The recording list'|trans }}",
            url: "{{ path('icsoc_recording_list_data') }}",
            postData: {param:jsonToString(getCondition())},
            colModel:[
                {% if listenSound == true or downSound == true %}
                    {name:'actions' , index:'actions' , label: '{{ 'actions'|trans }}' , width:80 , sortable:false,formatter:function(value,cell,row){
                        var fontStr = {% if listenSound == true %}"<i class='fa fa-youtube-play voice_prover' style='cursor:pointer;' onclick='listen(\""+row.call_id+"\",\""+row.agcdr_id+"\")'></i>"{% else %}''{% endif %};
                        fontStr += {% if downSound == true %}"&nbsp;&nbsp;<i class='fa fa-download' style='cursor:pointer;' onclick='downSound(\""+row.call_id+"\",\""+row.agcdr_id+"\")'></i>"{% else %}''{% endif %};
                        return fontStr;

                    }},
                {% endif %}
                {name:'ag_num' , index:'ag_num' , label: '{{ 'Agent Num'|trans }}' , width:80 , sortable:false , frozen:true},
                {name:'ag_name' , index:'ag_name' , label: '{{ 'Agent Name'|trans }}' , width:80 , sortable:false , frozen:true},
                {name:'ag_nickname' , index:'ag_nickname' , label: '{{ 'Agent Nickname'|trans }}' , width:90 , sortable:false , frozen:true},
                {% if isEnableGroup %}
                {name:'group_name' , index:'group_name' , label: '{{ 'Business Group'|trans }}' , width:80 , sortable:false ,fixed:true},
                {% endif %}
                {name:'que_name' , index:'que_name' , label: '{{ 'Queue'|trans }}' , width:100 , sortable:false },
                {name:'call_type' , index:'call_type' , label: '{{ 'Call type'|trans }}' , width:70 , sortable:false },
                {name:'serv_num' , index:'serv_num' , label: '{{ 'Relay number'|trans }}' ,width:100, sortable:false },
                {name:'ag_phone' , index:'ag_phone' , label: '{{ 'Agent Phone'|trans }}' ,width:120, sortable:false },
                {name:'cus_phone' , index:'cus_phone' , label: '{{ 'The customer number'|trans }}' , width:140 , sortable:false },
                {name:'start_time' , index:'start_time' , label: '{{ 'Start time'|trans }}' , width:140 , sortable:false },
                {name:'end_time' , index:'end_time' , label: '{{ 'End time'|trans }}' , width:140 , sortable:false },
                {name:'conn_secs' , index:'conn_secs' , label: '{{ 'The long recording time'|trans }}'  ,width:70 , sortable:false },
                {name:'evaluate' , index:'evaluate' , label: '{{ 'End type'|trans }}' , width:80 , sortable:false },
                {name:'id' , index:'id' , label: '' ,hidden:true, width:80 , sortable:true , key:true}
            ],
            {{ gridConfig() }}
            multiselect:false,
            loadComplete: function(xhr) {
                countRecord = xhr.records; //总记录数；
                var table = this;
                setTimeout(function(){
                    updatePagerIcons(table);
                }, 0);
                selectAll(isSelectAll);
                {#$('.voice_prover').popover({#}
                    {#'html':true,#}
                    {#'trigger':'click',#}
                    {#'content':'<audio id="sound_player" class="align-middle" style="margin-top: 8px;color: white;width: 200px;" autoplay="autoplay" controls="controls" ' +#}
                            {#'src="">{{ 'Your browser does not support the player'|trans }}</audio>',#}
                    {#'placement':'right'#}
                {#});#}
            },
            /*onSelectRow:function (rowIds, status) {
                //当取消选中 记录到变量中；
                processData(rowId, status);
                if (isSelectAll == 1) {
                    $("#selectNum").text(countRecord - isCancelSelect.length);
                } else {
                    $("#selectNum").text(isSelectedIds.length);
                }
            },*/
            /*onSelectAll:function (aRowids, status) {
                for (var i=0; i < aRowids.length; i++) {
                    var rowId = aRowids[i];
                    processData(rowId, status);
                }
                if (isSelectAll == 1) {
                    $("#selectNum").text(countRecord - isCancelSelect.length);
                } else {
                    $("#selectNum").text(isSelectedIds.length);
                }
            },*/
            pginput: false,
        });
        {{ gridNav(false,false,false,false,true,false) }}
        jQuery(grid_selector).navButtonAdd(
                pager_selector,
                {
                    caption:'{{ 'Export Csv'|trans }}',
                    buttonicon:'ace-icon fa fa-file-excel-o  primary',
                    onClickButton:function() {
                        var data = jsonToString(getCondition());
                        getSumMath(data,'csv');
                        //location.href = "{{ path('icsoc_recording_list_data', {'export': 'csv'})|raw }}&param="+jsonToString(getCondition());
                    }
                }
        ).navButtonAdd(
                pager_selector,
                {
                    caption:'{{ 'Export Excel'|trans }}',
                    buttonicon:'ace-icon fa fa-file-excel-o  primary',
                    onClickButton:function() {
                        var data = jsonToString(getCondition());
                        getSumMath(data,'excel');
                        //location.href = "{{ path('icsoc_recording_list_data', {'export': 'excel'})|raw }}&param="+jsonToString(getCondition());
                    }
                }
        ){% if downSound %}.navButtonAdd(
                pager_selector,
                {
                    caption:'下载 (只能下载前1000条数据)',
                    buttonicon:'ace-icon fa fa-download  primary',
                    onClickButton:function() {
                        var result = getCondition();
                        var start_time = transdate(result['start_time']);
                        //获取今天凌晨时间
                        var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
                        var timeEnd = timeStamp + 86399;
                        if (start_time < timeStamp || start_time > timeEnd) {
                            gritterAlert('{{ 'Prompt'|trans }}','只能下载今天的录音', 'error');
                            return;
                        }
                        var data = jsonToString(result);
                        location.href="{{ path('icsoc_recording_list_new_batch_down_data') }}?filter="+data+'&isall=0';
                    }
                }
        ){% endif %};
    });

    $(document).ready(function(){
        if (isSpecial == 1) {
            $('.forBaidu').hide();
        }
        $('#last_grid-pager').hide();
        $('#forAgent-ag_num').chosen({
            no_results_text:"{{ 'Not found'|trans }}",
            allow_single_deselect: true,
        });
        $.ajax({
            url: "{{ path('icsoc_report_getAgents') }}",
            type: 'post',
            data: {agentChosenSelect:'chosenSelect'},
            success: function (response) {
                $('#forAgent-ag_num').append(response);
                $("#forAgent-ag_num").trigger("chosen:updated");
            }
        });
        $('.normal-select').next().find('.chosen-search').hide();
    });

    /**
     * 重置
     */
    function resetBtn()
    {
        $('#searchForm')[0].reset();
        $(".chosen-select").trigger("chosen:updated");
        search();
    }

    /**
     * 搜索
     */
    function search()
    {
        $('#grid-table').setGridParam({page:1,postData:{param:jsonToString(getCondition())}}).trigger("reloadGrid");
    }

    /**
     * 获取搜索条件
     */
    function getCondition()
    {
        var $start_time = $('#start_time');
        var $end_time = $('#end_time');

        if (!$start_time.val()) {
            $start_time.parent().parent().addClass('has-error');
            $start_time.focus();
            return;
        }

        if (!$end_time.val()) {
            $end_time.parent().parent().addClass('has-error');
            $end_time.focus();
            return;
        }

        var param = {};
        param.ag_num = $.trim($('#forAgent-ag_num').val());
        param.call_type = $('#call_type').val();
        param.ag_phone =  $.trim($('#ag_phone').val());
        param.cus_phone =  $.trim($('#cus_phone').val());
        param.que_id = $('#que_id').val();
        param.start_time =  $.trim($('#start_time').val());
        param.end_time =  $.trim($('#end_time').val());
        param.serv_num = $.trim($('#serv_num').val());
       // param.end_result =  $.trim($('#end_result').val());
        var evaluates = $.trim($('#evaluates').val());
        evaluates.length >= 1 ?  param.evaluates = evaluates : '';
        param.ssecs =  $.trim($('#ssecs').val());
        param.esecs =  $.trim($('#esecs').val());
        {% if isEnableGroup %}
        param.group_id = $('#group_id').val();
        {% endif %}
        return param;
    }

    /**
     * 设置时间
     *
     * @param type
     */
    function fnSetTime(type)
    {
        var $start_time = $('#start_time');
        var $end_time = $('#end_time');

        switch (type) {
            case 1:
                $start_time.val('{{ date.yestoday.start }}');
                $end_time.val('{{ date.yestoday.end }}');
                break;
            case 2:
                $start_time.val('{{ date.today.start }}');
                $end_time.val('{{ date.today.end }}');
                break;
            case 3:
                $start_time.val('{{ date.lastweek.start }}');
                $end_time.val('{{ date.lastweek.end }}');
                break;
            case 4:
                $start_time.val('{{ date.thisweek.start }}');
                $end_time.val('{{ date.thisweek.end }}');
                break;
            case 5:
                $start_time.val('{{ date.lastmonth.start }}');
                $end_time.val('{{ date.lastmonth.end }}');
                break;
            case 6:
                $start_time.val('{{ date.thismonth.start }}');
                $end_time.val('{{ date.thismonth.end }}');
                break;
            case 7:
                $start_time.val('{{ date.thisyear.start }}');
                $end_time.val('{{ date.thisyear.end }}');
                break;
            case 8:
                $start_time.val('{{ date.lastyear.start }}');
                $end_time.val('{{ date.lastyear.end }}');
                break;
        }

        search();
    }

    function listen(id, agcdr_id)
    {
        $.ajax({
            type:"get",
            url: '{{ path('icsoc_recording_list_play_voice') }}',
            data: {flag:2, callid: id, agcdr_id: agcdr_id},
            success: function(res){
                if (res.err) {
                    gritterAlert('{{ 'Prompt'|trans }}','{{ 'File not exist'|trans }}', 'error');
                } else {
                    $('#sound_player').attr("src", res.url);
                }
            }
        });
    }
    function downSound(id, agcdr_id)
    {
        $.ajax({
            type:"get",
            url: '{{ path('icsoc_recording_list_play_voice') }}',
            data: {flag:2, callid: id, agcdr_id: agcdr_id},
            success: function(res){
                if (res.err) {
                    gritterAlert('{{ 'Prompt'|trans }}','{{ 'File not exist'|trans }}', 'error');
                } else {
                    window.open(res.url);
                }
            }
        });
    }
    function selectAll(flag, v)
    {
        //如果是点击按钮来的就清空；
        if (v) {
            isCancelSelect = [];
            isSelectedIds = [];
            $('#selectNum').text(countRecord);
        }
        isSelectAll = flag;
        var grid = $('#grid-table');
        if (flag == 1) {
            //全选
            grid.jqGrid('resetSelection');
            var ids = grid.getDataIDs();
            if (ids.length == 0 && countRecord == 0) {
                isCancelSelect = [];
                isSelectedIds = [];
                $('#selectNum').text(countRecord); //如果记录为空；置零；
                return ;
            }
            for (var i=0, il=ids.length; i < il; i++) {
                if (isCancelSelect.indexOf(ids[i]) == -1) {
                    grid.jqGrid('setSelection',ids[i], true);
                }
            }
        } else if (flag == 3) {
            //普通点击全选
            if (countRecord == 0) {
                isCancelSelect = [];
                isSelectedIds = [];
                $('#selectNum').text(countRecord); //如果记录为空；置零
                return ;
            }
            for (var i=0, il=isSelectedIds.length; i < il; i++) {
                grid.jqGrid('setSelection',isSelectedIds[i], true);
            }
        } else {
            isCancelSelect = [];
            isSelectedIds = [];
            isSelectAll = 3;//重置成3
            $('#selectNum').text(0);
            grid.jqGrid('resetSelection');
        }
    }

    function processData(rowId, status)
    {
        if (!status && isCancelSelect.indexOf(rowId) == -1) {
            isCancelSelect.push(rowId);
        } else if (status && isCancelSelect.indexOf(rowId) != -1) {
            //如果又选中了就要从isCancelSelect中去掉
            var index = isCancelSelect.indexOf(rowId);
            isCancelSelect.remove(index);
        }
        if (status && isSelectAll == 3 && isSelectedIds.indexOf(rowId) == -1) {
            isSelectedIds.push(rowId);
        } else if (isSelectAll == 3 && !status) {
            var index = isSelectedIds.indexOf(rowId);
            isSelectedIds.remove(index);
        }
    }

    /**
     * 批量下载
     * @returns {boolean}
     */
    function batchDownload()
    {
        if ((isSelectedIds.length < 1 && isSelectAll==3) || countRecord <=0 ) {
            gritterAlert('{{ 'Prompt'|trans }}','{{ 'Please check the data'|trans }}', 'error');
            return ;
        }
        var search =$('#grid-table').jqGrid('getGridParam');
        var postData = '';
        if (isSelectAll==1) {
            //区分按钮；//获取grid 的搜索条件；
            postData = typeof(search.postData.param) != 'undefined' ? search.postData.param : '';
            //如果是全选；就得限制时间范围；
            var data = stringToJSON(postData);
            var start_time = data.start_time;
            var end_time = data.end_time;
            start_time = datetime_to_int(start_time);
            end_time = datetime_to_int(end_time);
            /*if ((end_time - start_time)/(3600*24) > 1) {
                gritterAlert('{{ 'Prompt'|trans }}','{{ 'One day data only download'|trans }}', 'error');
                return false;
            }*/
        }
        var isAll = isSelectAll == 1 ? 1 : 0;

        location.href="{{ path('icsoc_recording_list_new_batch_down_data') }}?filter="+postData+'&ids='+isSelectedIds+'&isall='+isAll+'&iscancelIds='+isCancelSelect;
    }

    //创建导出任务
    function addDownloadWorlk(type,data){
        $.ajax({
            url: "{{ path('icsoc_recording_list_data') }}",
            dataType: 'json',
            data: {'export': type,'param':data,'big':true},
            type: 'post',
            success: function (e) {
                if(e['code'] == 200) {
                    $( "#dialogconfirm" ).removeClass('hide').dialog({
                        resizable: false,
                        modal: false,
                        title_html: true,
                        title:"提示"
                    });
                } else {
                    gritterAlert('{{ 'Prompt'|trans }}', e['message'],'error');
                }
            }
        })
    }
    //计算数量 判断用哪一种导出方式
    function getSumMath(data,type){
        $.ajax({
            url: "{{ path('icsoc_recording_list_data') }}",
            dataType: 'json',
            data: {'param':data, 'sum':true},
            type: 'post',
            success: function (e) {
                if(e['code'] == 200) {
                    if(e['count'] < {{ max_export_num }}) {
                        location.href = "{{ path('icsoc_recording_list_data')}}?export="+type+"&param="+jsonToString(getCondition());
                    } else {
                        addDownloadWorlk(type,data);
                    }
                } else {
                    gritterAlert('{{ 'Prompt'|trans }}', e['message'],'error');
                }
            }
        })
    }

    function myBrowser() {
        $(document).bind("contextmenu",function(e){
            return false;
        });
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
        //谷歌浏览器
        if (userAgent.indexOf("Chrome") > -1){
            $('audio').addClass('audios');
        }
    }

    function showTab(name, url)
    {
        window.parent.createTab(name, url);
        $('#dialogconfirm').dialog('close');
    }
    //时间转换时间戳
    function transdate(endTime){
        var date=new Date();
        date.setFullYear(endTime.substring(0,4));
        date.setMonth(endTime.substring(5,7)-1);
        date.setDate(endTime.substring(8,10));
        date.setHours(endTime.substring(11,13));
        date.setMinutes(endTime.substring(14,16));
        date.setSeconds(endTime.substring(17,19));
        return Date.parse(date)/1000;
    }
    </script>
{% endblock %}